package cn.yuanqiao.archive.wenjianzhengli.utils;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author zjj
 * @date 2023/9/1
 */
public class RedisDistributedLock {
    private static final String LOCK_KEY_PREFIX = "lock:";
    private static final long LOCK_EXPIRE_TIME = 600000L; //自动失效时间，10分钟

    private RedisTemplate redisTemplate;
    private String lockKey;
    private String lockValue;
    private boolean locked = false;

    public RedisDistributedLock(RedisTemplate redisTemplate, String lockKey, String lockValue) {
        this.redisTemplate = redisTemplate;
        this.lockKey = LOCK_KEY_PREFIX + lockKey;
        this.lockValue = lockValue;
    }

    public boolean lock() {
        if (redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue)) {
            redisTemplate.expire(lockKey, LOCK_EXPIRE_TIME, TimeUnit.MILLISECONDS);
            locked = true;
            return true;
        } else {
            return false;
        }
    }

    public void unlock() {
        if (locked) {
            redisTemplate.delete(lockKey);
        }
    }
}
